package com.zl.learning.regex;

import org.junit.Test;

import java.io.File;
import java.io.FileFilter;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhaolei on 2017/6/14.
 */
public class TestRegularExpression {

    //查找以Java开头,任意结尾的字符串
    @Test
    public void test1() {
        Matcher matcher = Pattern.compile("^Java.*").matcher("Java不是人");
        boolean b = matcher.matches();
        //当条件满足时，将返回true，否则返回false
        System.out.println(b);
    }

    //以多条件分割字符串时
    @Test
    public void test2() {
        String[] strs = Pattern.compile("[, |]+").split("Java Hello World  Java,Hello,,World|Sun");
        for (int i = 0; i < strs.length; i++) {
            System.out.println(strs[i]);
        }
    }

    //文字替换（首次出现字符）
    @Test
    public void test3() {
        Pattern pattern = Pattern.compile("正则表达式");
        Matcher matcher = pattern.matcher("正则表达式 Hello World,正则表达式 Hello World");
        //替换第一个符合正则的数据
        System.out.println(matcher.replaceFirst("Java"));
    }

    //文字替换全部
    @Test
    public void test4() {
        Pattern pattern = Pattern.compile("正则表达式");
        Matcher matcher = pattern.matcher("正则表达式 Hello World,正则表达式 Hello World");
        System.out.println(matcher.replaceAll("Java"));
    }

    //文字替换（置换字符）
    @Test
    public void test5() {
        Pattern pattern = Pattern.compile("正则表达式");
        Matcher matcher = pattern.matcher("正则表达式 Hello World,正则表达式 Hello World ");
        StringBuffer stringBuffer = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(stringBuffer, "java");
        }
        matcher.appendTail(stringBuffer);
        System.out.println(stringBuffer.toString());
    }

    //验证是否为邮箱地址
    @Test
    public void test6() {
        String str = "ceponline@yahoo.com.cn";
        Pattern pattern = Pattern.compile("[//w//.//-]+@([//w//-]+//.)+[//w//-]+", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        System.out.println(matcher.matches());
    }

    //去除html标记
    @Test
    public void test7() {
        Pattern pattern = Pattern.compile("<.+?>", Pattern.DOTALL);
        Matcher matcher = pattern.matcher("<a href=index.html>主页</a>");
        String string = matcher.replaceAll("");
        System.out.println(string);
    }

    //查找html中对应条件字符串
    @Test
    public void test8() {
        Pattern pattern = Pattern.compile("href=(.+?.html)");
        Matcher matcher = pattern.matcher("<a href=index.html>主页</a>");
        if (matcher.find())
            System.out.println(matcher.group(1));
    }

    //截取http://地址
    @Test
    public void test9() {
        Pattern pattern = Pattern.compile("\"(http://|https://){1}[//w//.//-/:]+\"");
        Matcher matcher = pattern.matcher("dsdsds<http://dsds//gfgffdfd>fdf");
        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
            buffer.append(matcher.group());
            buffer.append("/r/n");
            System.out.println(buffer.toString());
        }
    }

    //替换指定{}中文字
    @Test
    public void test10() {
        String str = "Java目前的发展史是由{0}年-{1}年";
        String[][] object = {new String[]{"//{0//}", "1995"}, new String[]{"//{1//}", "2007"}};
        System.out.println(replace(str, object));

    }

    @Test
    public void test11() {
        String str = "/ogin2/auth/token";
        Pattern pattern = Pattern.compile("^((?!login).)*$");
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            System.out.println(matcher.groupCount());
            System.out.println(matcher.group(0));
        }
    }

    public static String replace(final String sourceString, Object[] object) {
        String temp = sourceString;
        for (int i = 0; i < object.length; i++) {
            String[] result = (String[]) object[i];
            Pattern pattern = Pattern.compile(result[0]);
            Matcher matcher = pattern.matcher(temp);
            temp = matcher.replaceAll(result[1]);
        }
        return temp;
    }

    //以正则条件查询指定目录下文件
    static class FilesAnalyze {
        private ArrayList files = new ArrayList();
        //用于承载文件路径
        private String _path;
        //用于承载未合并的正则公式
        private String _regexp;

        class MyFileFilter implements FileFilter {

            /**
             * 匹配文件名称
             */
            public boolean accept(File file) {
                try {
                    Matcher match = Pattern.compile(_regexp).matcher(file.getName());
                    return match.matches();
                } catch (Exception e) {
                    return true;
                }
            }
        }

        /**
         * 解析输入流
         */
        FilesAnalyze(String path, String regexp) {
            getFileName(path, regexp);
        }

        /**
         * 分析文件名并加入files
         */
        private void getFileName(String path, String regexp) {
            //目录
            _path = path;
            _regexp = regexp;
            File directory = new File(_path);
            File[] filesFile = directory.listFiles(new MyFileFilter());
            if (filesFile == null) return;
            for (int j = 0; j < filesFile.length; j++) {
                files.add(filesFile[j]);
            }
            return;
        }

        /**
         * 显示输出信息
         *
         * @param out
         */
        public void print(PrintStream out) {
            Iterator elements = files.iterator();
            while (elements.hasNext()) {
                File file = (File) elements.next();
                out.println(file.getPath());
            }
        }

        public static void output(String path, String regexp) {

            FilesAnalyze fileGroup1 = new FilesAnalyze(path, regexp);
            fileGroup1.print(System.out);
        }

        public static void main(String[] args) {
            output("C://", "[A-z|.]*");
        }
    }

}
